package com.ruoyi.web.controller.letchat;

import com.google.gson.Gson;
import com.ruoyi.common.core.domain.ResponseData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.common.core.domain.entity.OutUser;
import com.ruoyi.system.domain.dto.WeChatSessionModel;
import com.ruoyi.system.domain.resp.WechatLogInResp;
import com.ruoyi.system.req.WechatLogInReq;
import com.ruoyi.system.service.IOutUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;


@RestController
@RequestMapping("/letchat")
public class WechatController {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    //在开发者平台中获取APPID和APPSECRET
    private static final String APPID= "wxa470b7a9a7ac3bff";
    private static final String APPSECRET = "db37922609d9005c2bcc21824b3b4836";
    @Autowired
    private IOutUserService outUserService;
    @Autowired
    TokenService tokenService;
    @PostMapping("/login")
    @ResponseBody
    public ResponseData login(@RequestBody WechatLogInReq req){
        String openid = null;
        String session_key = null;
        String errcode = null;
        String errmsg = null;
        WeChatSessionModel weChatSessionModel;

        //微信服务器的接口路径
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+APPID+ "&secret="+APPSECRET+"&js_code="+ req.getCode() +"&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        //进行网络请求,访问微信服务器接口
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        //根据返回值进行后续操作
        WechatLogInResp wechatLogInResp=new WechatLogInResp();

        if(responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
            String sessionData = responseEntity.getBody();
            Gson gson = new Gson();
            //将json字符串转化为实体类;
            weChatSessionModel = gson.fromJson(sessionData, WeChatSessionModel.class);
            //获取用户的唯一标识
//            openid = weChatSessionModel.getOpenid();
            openid=String.valueOf(System.currentTimeMillis());
            //获取会话秘钥（具有时效性，用户登录的临时通行证）
            //登录后前端的每次接口请求都需带上session_key
//            session_key = weChatSessionModel.getSession_key();
            session_key=String.valueOf(System.currentTimeMillis());
            //获取错误码
            errcode = weChatSessionModel.getErrcode();
            //获取错误信息
            errmsg = weChatSessionModel.getErrmsg();
            wechatLogInResp.setSession_key(session_key);
        }
        try{
            if (openid == null || session_key == null){
                return ResponseData.error("errcode: " + errcode + ";errmsg: " + errmsg);
            }
            OutUser outUser = outUserService.login(openid);
            if(outUser==null){
                OutUser addOutUser=new OutUser();
                BeanUtils.copyProperties(req,addOutUser);
                addOutUser.setUserName(req.getNickName());
                addOutUser.setOpenid(openid);
                int flag = outUserService.insertOutUser(addOutUser);
                if(flag ==1){
                    LoginUser loginUser=new LoginUser(addOutUser);
                    loginUser.setToken(session_key);
                    return ResponseData.success(tokenService.createToken(loginUser));
                }
                else {
                    return ResponseData.error("用户login失败！");
                }
            }
            else{
                LoginUser loginUser=new LoginUser(outUser);
                loginUser.setToken(session_key);
                return ResponseData.success(tokenService.createToken(loginUser));
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            e.printStackTrace();
            return ResponseData.error( "添加用户信息Exception");
        }
    }
    @PostMapping("/update")
    @ResponseBody
    public ResponseData hello(@RequestBody OutUser outUser ){
        outUserService.updateOutUserById(outUser);
        return ResponseData.success( "添加用户信息success");

    }
}
